package com.adee.netty.lengthfieldbased;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LoggingHandler;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;

public class NettyClient {

    static CountDownLatch connected = new CountDownLatch(1);

    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup(1);
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler());
                        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(
                                100,0,
                                4,0,0));
                    }
                });
        ChannelFuture future = bootstrap.connect("127.0.0.1", 8011).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                connected.countDown();
            }
        });
        // 等待连接成功
        connected.await();

        Channel ch = future.channel();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
            ByteBufAllocator alloc = ch.alloc();
            ByteBuf buf = alloc.buffer();
            buf.writeInt(bytes.length);
            buf.writeBytes(bytes);
            ch.writeAndFlush(buf);
//            System.out.println(String.format("【我】 <%s> %s", ch.localAddress(), s));
            System.out.println("发送消息：" + s);
        }
    }
}
